import {
  getInvestInfo, getBranchName, getProductElig, getContractById, setProductElig, signWithContent
} from '@/api/index';
import DZUtils from '@/utils/DZUtils';
import Common from '@/utils/common';

export default {
  data() {
    return {
      // type: 记录适当性，默认普通投资者三要素不匹配签署不适当警示；普通投资者三要素匹配签署投资确认书，可课下单
      // type: 为2，私募、信托基金，投资者三要素不匹配提示后禁止购买；否则签署投资确认书后可下单
      type: String,
      branchInfo: {},
      fourFac: {},
      userFourFac: {},
      prodFourFac: {},
      isFourFacPP: false
    };
  },
  methods: {
    async inadequacyCheck(type) {
      this.type = type || '';
      const promises = [];
      promises.push(getInvestInfo());
      promises.push(getProductElig(this.prodCode));
      // promises.push(getBranchName(this.userInfo.branchNo));

      Promise.all(promises).then((response) => {
        const [res1, res2, res3] = response;
        if (res1.dataSet.length > 0 && res2.dataSet.length > 0) {
          const data1 = res1.dataSet[0];
          this.userInfo.profFlag = data1.isProfessionFlag;
          // 获取用户所在营业部
          // if (res3.returnCode === '0' && res3.dataSet[0]) {
          //   this.branchInfo.branchName = res3.dataSet[0].branchName;
          //   this.branchInfo.branchType = res3.dataSet[0].branchType;
          // }

          // 解析用户三要素
          this.userFourFac = {
            user_risk: Common.parseUserRisk(data1.userRiskLevel),
            user_term: Common.parseUserTerm(data1.userInvestTerm),
            user_kind: Common.parseUserKind(data1.userInvestKind),
          };

          // 解析产品三要素
          this.prodFourFac = {
            prod_risk: Common.parseProdRisk(res2.dataSet[0].productRiskLevel),
            prod_term: Common.parseProdTerm(res2.dataSet[0].investTerm),
            prod_type: Common.parseProdKind(res2.dataSet[0].investType),
          };

          this.fourFac = {
            ...this.branchInfo,
            ...res2.dataSet[0],
            ...this.userFourFac,
            ...this.prodFourFac
          };

          DZUtils.setStorage('batchNo', res2.dataSet[0].batchNo);
          this.isFourFacPP = String(this.fourFac.riskFlag) === '1' && String(this.fourFac.typeFlag) === '1' && String(this.fourFac.termFlag) === '1';

          console.log(this.fourFac, this.isFourFacPP);
          if (this.type && this.type === '2') {
            // 私募、信托适当性检查
            if (this.userInfo.profFlag === '0' && !this.isFourFacPP) {
              // 私募、信托基金，三要素不匹配，禁止购买
              this.inadequacyResultError();
            } else if (this.userInfo.profFlag === '0' && this.isFourFacPP) {
              // 三要素匹配
              this.checkInadequacyConfirm();
            } else {
              const adequacyParam = { batchNo: this.fourFac.batchNo, isFourFacPP: this.isFourFacPP };
              this.inadequacyCallback(adequacyParam);
            }
          } else {
            if (this.userInfo.profFlag === '0' && !this.isFourFacPP) {
              // 普通投资者，三要素不匹配；
              this.checkInadequacyResult();
            } else if (this.userInfo.profFlag === '0' && this.isFourFacPP) {
              // 普通投资者，且三要素匹配
              this.checkInadequacyConfirm();
            } else {
              // 专业投资者不需要三要素匹配
              const adequacyParam = { batchNo: this.fourFac.batchNo, profFlag: this.userInfo.profFlag, isFourFacPP: this.isFourFacPP };
              // 执行页面组件inadequacyCallback方法
              this.inadequacyCallback(adequacyParam);
            }
          }
        } else {
          DZUtils.iAlert('错误提示', `${res1.returnInfo} ${res2.returnInfo}`);
        }
      });
    },
    async checkInadequacyResult() {
      const { inadequacyResultInfo, inadequacyResultInfo2 } = require('@/components/contracts/agreement.js');
      const inadequacyInfo = inadequacyResultInfo(this.fourFac);
      const inadequacyInfo2 = inadequacyResultInfo2(this.fourFac);
      const res = await getContractById({ type: 'inadequacy' });
      let id = '';
      let html = '';
      if (res.returnCode === '0' && res.dataSet[0]) {
        id = res.dataSet[0].id;
        html = res.dataSet[0].templateContent.replace(/userName/g, this.userInfo.userName)
          .replace(/fundAccount/g, this.userInfo.fundAccount)
          .replace(/prodCode/g, this.prodCode)
          .replace(/prodName/g, this.prodInfo.prodName || this.fourFac.productName)
          .replace(/inadequacyResultInfo/, inadequacyInfo)
          .replace(/inadequacyResultInfo2/, inadequacyInfo2);
      }

      // 签署金融产品不适当警示书
      const title = '金融产品不适当警示及投资者确认书';

      DZUtils.iConfirm(title, html, '确认并下一步', '退出购买', () => {
        this.inadequacyMark(id, html);
      }, () => {
        // 执行页面组件inadequacyCancel方法
        this.inadequacyCancel && this.inadequacyCancel();
      });
    },
    async checkInadequacyConfirm() {
      const { adequacyConfirmInfo } = require('@/components/contracts/agreement.js');
      const adequacyInfo = adequacyConfirmInfo(this.fourFac);
      const res = await getContractById({ type: 'adequacy' });
      let id = '';
      let html = '';
      if (res.returnCode === '0' && res.dataSet[0]) {
        id = res.dataSet[0].id;
        html = res.dataSet[0].templateContent.replace(/userName/g, this.userInfo.userName)
          .replace(/fundAccount/g, this.userInfo.fundAccount)
          .replace(/prodCode/g, this.prodCode)
          .replace(/prodName/g, this.prodInfo.prodName || this.fourFac.productName)
          .replace(/adequacyConfirmInfo/g, adequacyInfo);
      }
      const title = '适当性评估结果确认书';

      DZUtils.iAlert(title, html, '确定', () => {
        this.inadequacyMark(id, html);
      });
    },
    inadequacyResultError() {
      this.$nextTick(() => {
        const { inadequacyError } = require('@/components/contracts/agreement.js');
        const html = inadequacyError(this.fourFac);
        // 签署金融产品不适当警示书
        DZUtils.iAlert('温馨提示', html, '我知道了', () => {
          // 执行页面组件inadequacyCancel方法
          this.inadequacyCancel && this.inadequacyCancel();
        });
      });
    },
    // 供父组件调用的方法，留痕
    async inadequacyMark(id, html) {
      const param = {
        id,
        batchNo: this.fourFac.batchNo,
        content: html.replace(/<[^>]+>/g, ''),
        source: 'inadequacyCheck'
      };
      Promise.all([setProductElig(param), signWithContent(param)])
        .then(([res, res2]) => {
          if (res.returnCode === '0' && res2.returnCode === '0') {
            console.log('柜台留痕，留痕成功');
            console.log('协议中心留痕，留痕成功');

            const adequacyParam = { batchNo: this.fourFac.batchNo, isFourFacPP: this.isFourFacPP };
            this.inadequacyCallback(adequacyParam);
          } else {
            DZUtils.iDialog(`${res.returnInfo}<br/>${res2.returnInfo}`);
          }
        });
    }
  }
};